from datetime import date, datetime
from google.appengine.api.urlfetch import fetch
from horseanalysis.lib.hkjc_fetcher.fetcher_base import FetcherBase
from horseanalysis.model.win_place import WinPlace
from horseanalysis.model.race import Race
import re

class WinPlaceFetcher(FetcherBase):
  def getUrl(self):
    return "http://bet.hkjc.com/racing/getXML.aspx?type=jcbwracing_winplaodds&date=%(date_query)s&venue=%(venue)s&start=%(race_no)d&end=%(race_no)d&data=" % \
      {'date_query': self.date_query, 'venue': self.venue, 'race_no': self.race_no}
    
  def getData(self):
    data = fetch(self.getUrl())
    self.batch_time.update_win_place(data.content)
    return data.content
    
  def getResult(self):
    data = self.getData()
    groups = data.split('#PLA;')
    win = groups[0]
    place = groups[1]
    win_place_items = {}
    for result in re.finditer(r"([0-9]*)=([0-9.]*)=([0-9.]*)", win):
      item = {'horse_no':int(result.group(1)), 'win':float(result.group(2))}
      win_place_items[item['horse_no']] = item
    
    for result in re.finditer(r"([0-9]*)=([0-9.]*)=([0-9.]*)", place):
      win_place_items[int(result.group(1))]['place'] = float(result.group(2))
      
    for item in win_place_items:
      WinPlace.create_new_entry(self.race, self.batch_time, win_place_items[item]['horse_no'], win_place_items[item]['win'], win_place_items[item]['place'])
      
    return win_place_items